import request from "@/axios"
import { LoginInfo, loginRes, RefreshToken } from "./types"
import { ResponseData } from "../../../../constants"
import { useUserStoreWithOut } from "@/store/modules/user"
import { ElMessage } from "element-plus"

enum Api {
  Login = '/auth/login',
  refreshToken = "/auth/refreshToken",
  getCaptchaImage = "/common/getCaptchaImage",
  Register = "/auth/register"
}

// 获取验证码
export const getCaptchaImage = () => {
  return request.get<ResponseData>(Api.getCaptchaImage)
}

// 登录
export const login = (params: LoginInfo & { code: string; uuid: string } ) => {
  return request.post<ResponseData<loginRes>>(Api.Login, { ...params })
}

// 注册
export const register = (params: any) => {
  return request.post<ResponseData>(Api.Register, { ...params })
}

// 刷新token
export const refreshTokenApi = async () => {
  const userStore = useUserStoreWithOut()

  const ret = await request.post<ResponseData<RefreshToken>>(Api.refreshToken, {}, {
    headers: {
      [userStore.getTokenKey ?? 'Authorization']: userStore.getRefreshToken ?? ''
    }
  })
  if (ret.code === 200) {
    const { access_token, refresh_token } = ret.data
    userStore.setAccessToken("bearer " + access_token)
    userStore.setRefreshToken("bearer " + refresh_token)
    return true
  } else {
    userStore.logout()
    ElMessage.info("登录已过期，请重新登录")
    return false
  }
}




